// See https://aka.ms/new-console-template for more information
using Microsoft.Extensions.DependencyInjection;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using StarAIHelper;

Console.Title = "AI大模型添加搜索引擎功能.NET";
Console.WriteLine("Hello, 欢迎使用基于AI大模型添加搜索引擎功能.NET");
var apiKey = "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
var apiHost = "https://api.openai.com/";

var kernelBuilder = Kernel.CreateBuilder().AddOpenAIChatCompletion(modelId: "gpt-4o", apiKey: apiKey, httpClient: new HttpClient(new AiHttpClientHandler(apiHost)));

kernelBuilder.Services.AddHttpClient();

var kernel = kernelBuilder.Build();

kernel.Plugins.AddFromType<HttpClientFunction>(serviceProvider: kernel.Services);

var chat = kernel.GetRequiredService<IChatCompletionService>();

var openAIPromptExecutionSettings = new OpenAIPromptExecutionSettings()
{
    ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions
};

while (true)
{
    Console.WriteLine("请输入您的问题：");
    var str = Console.ReadLine();
    if (str == "exit")
    {
        break;
    }
    if (string.IsNullOrWhiteSpace(str))
    {
        continue;
    }
    Console.WriteLine("正在思考中……");
    var chatHistory = new ChatHistory();
    chatHistory.AddUserMessage(str);
    var msg = "";
    await foreach (var item in chat.GetStreamingChatMessageContentsAsync(chatHistory, openAIPromptExecutionSettings, kernel))
    {
        Console.Write(item?.Content);
        msg += item?.Content;
    }
    Console.WriteLine("\r\n");
    Console.WriteLine("最终结果：");
    Console.ForegroundColor = ConsoleColor.Green;
    Console.WriteLine(msg);
    Console.ForegroundColor = ConsoleColor.Gray;
    Console.WriteLine("\r\n");
    Console.WriteLine("回答结束");
    Console.WriteLine("\r\n");
}